import axios from 'axios';
import { useMainStore } from '@/stores/mainStore';
import router from '@/router';
import { ElMessage } from 'element-plus';


const apiClient = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL || '/api',
  timeout: 60000,
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    const store = useMainStore();
    const token = store.getToken();
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
     console.log(response);



     const res = response.data;
     if (res.code !== 200) {
      ElMessage.error(res.msg || '系统错误');
      return Promise.reject(res); // 阻止继续 then 流
    }
    return res.data; 

  },
  (error) => {
    const store = useMainStore();
    if (error.response?.status === 401) {
      store.removeToken(); // 清除 token
      router.push('/login'); // 跳转登录
    }
    return Promise.reject(error);
  }
);

export default apiClient;